package cn.com.fuhuitong.main.order.ui.fragment

import android.os.Bundle
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import cn.com.fuhuitong.R
import cn.com.fuhuitong.app.AppConstance
import cn.com.fuhuitong.app.BaseApplication
import cn.com.fuhuitong.aroute.ARouteConstance
import cn.com.fuhuitong.base.EmptyContent
import cn.com.fuhuitong.entity.EmptyState
import cn.com.fuhuitong.entity.MainBean
import cn.com.fuhuitong.entity.OrderAction
import cn.com.fuhuitong.http.HttpResponseStatus
import cn.com.fuhuitong.main.base.ViewModeFragment
import cn.com.fuhuitong.main.order.adapter.OVT
import cn.com.fuhuitong.main.order.adapter.OrderListAdapter
import cn.com.fuhuitong.main.order.vm.OrderViewModel
import com.alibaba.android.arouter.launcher.ARouter
import com.alibaba.android.vlayout.layout.LinearLayoutHelper
import com.scwang.smart.refresh.footer.ClassicsFooter
import com.scwang.smart.refresh.header.MaterialHeader
import kotlinx.android.synthetic.main.fragment_order_list.*
import org.greenrobot.eventbus.EventBus


class OrderListFragment : ViewModeFragment<OrderViewModel>() {

//    enum class OrderAction {
//        CANCEL, CONFIRM, DELETE, PAYMENT
//    }

    companion object {
        private const val TYPE = "type"
        fun newInstance(type: Int): OrderListFragment {
            val fragment = OrderListFragment()
            fragment.arguments = Bundle().apply {
                putInt(TYPE, type)
            }
            return fragment
        }
    }

    private var isOrderListData: Boolean = false

    private lateinit var orderListAdapter: OrderListAdapter

    override fun viewModel(): OrderViewModel = ViewModelProvider(
        this, ViewModelProvider.AndroidViewModelFactory(BaseApplication.INSTANCE)
    ).get(OrderViewModel::class.java)

    override val layoutResId: Int
        get() = R.layout.fragment_order_list

    override fun initView() {


        this.initViewRecyclerAdapter(
            recycler_order_list, arrayOf(OVT.ORDER_LIST.ordinal)
        )

        delegateAdapter.addAdapter(OrderListAdapter(
            requireContext(), LinearLayoutHelper(resources.getDimensionPixelSize(R.dimen.dp_10))
        ).apply {
            orderListAdapter = this
        })

        orderListAdapter.setOnItemChildClickListener { view, _, orderListEntity ->
            when (view.id) {
                R.id.text_order_time -> {
                    //跳转订单详情
                    ARouter.getInstance().build(ARouteConstance.ACTIVITY_URL_ORDER_DETAILS)
                        .withInt(AppConstance.BUNDLE_ORDER_ID, orderListEntity.id)
                        .navigation()
                }
                R.id.recycler_order_goods -> {
                    //跳转订单详情
                    ARouter.getInstance().build(ARouteConstance.ACTIVITY_URL_ORDER_DETAILS)
                        .withInt(AppConstance.BUNDLE_ORDER_ID, orderListEntity.id)
                        .navigation()
                }
                R.id.text_order_action -> {
                    //其他行为（删除订单、去付款、确认收货）
                    when (orderListEntity.status) {
                        1 -> {
                            //去付款
                            viewModel.orderPay(orderListEntity.id)
                        }
                        2 -> {
                            //确认收货
                            viewModel.orderConfirm(orderListEntity.id)
                        }
                        3 -> {
                            //删除订单
                        }
                    }
                }
                R.id.text_order_cancel -> {
                    //取消订单
                    viewModel.orderCancel(orderListEntity.id)
                }
            }
        }

        with(smartRefreshLayout) {
            setRefreshHeader(MaterialHeader(requireContext()))
            setRefreshFooter(ClassicsFooter(requireContext()))
        }
        smartRefreshLayout.setOnRefreshListener {
            smartRefreshLayout.finishRefresh(true)
            viewModel.orderList(arguments?.getInt(TYPE) ?: 0, true)
        }
        smartRefreshLayout.setOnLoadMoreListener {
            smartRefreshLayout.finishLoadMore(true)
            viewModel.orderList(arguments?.getInt(TYPE) ?: 0)
        }
    }

    override fun initViewMode() {

        viewModel.orderListDataLiveData.observe(viewLifecycleOwner, Observer { response ->

            val dataLength: Int = response.response?.data?.size ?: 0

            smartRefreshLayout.isEnabled = dataLength != 0
            if (dataLength < 20) {
                smartRefreshLayout.finishLoadMoreWithNoMoreData()
            }

            when (response.status) {
                HttpResponseStatus.Status.START -> {
                    if (dataLength == 0) {
                        showLoadEmptyView()
                    }
                }
                HttpResponseStatus.Status.SUCCESS -> {
                    if (dataLength == 0) {
                        showNullEmptyView(EmptyContent("重新加载", "暂无数据"))
                    } else {
                        hideEmptyView()
                    }
                }
                HttpResponseStatus.Status.FAILURE -> {
                    if (dataLength == 0) {
                        showErrorEmptyView(EmptyContent("重新加载", response.statusTip))
                    }
                    toast(response.statusTip)
                }
            }


            if (response.status != HttpResponseStatus.Status.SUCCESS)
                return@Observer
            response.response?.let {
                isOrderListData = true
                if (it.loadMore) {
                    orderListAdapter.setAddDataMore(it.data)
                } else {
                    orderListAdapter.setAddDataNew(it.data)
                }
            }
        })

        viewModel.baseDataLiveData.observe(viewLifecycleOwner, Observer { response ->
            handlerResponseLoading(response.status, response.statusTip)
            if (response.status != HttpResponseStatus.Status.SUCCESS)
                return@Observer
            toast(response.response?.msg ?: "操作成功")
        })


        viewModel.payDataLiveData.observe(this, Observer { response ->
            handlerResponseLoading(response.status, response.statusTip)
            if (response.status != HttpResponseStatus.Status.SUCCESS)
                return@Observer
            response.response?.data?.let {
                ARouter.getInstance().build(ARouteConstance.ACTIVITY_URL_ORDER_PAY_WAIT)
                    .withSerializable(AppConstance.BUNDLE_ORDER_PAY, it)
                    .navigation()
            }
        })

    }

    override fun initData() {
        viewModel.orderList(arguments?.getInt(TYPE) ?: 0, true)
    }

    override fun onLoadingEmptyView(state: EmptyState) {
        super.onLoadingEmptyView(state)
        viewModel.orderList(arguments?.getInt(TYPE) ?: 0, true)
    }

    override fun onEventMainThread(eventBus: MainBean<*, *>) {
        super.onEventMainThread(eventBus)
        if (eventBus.type !is OrderAction) {
            return
        }
        if (isOrderListData) {
            viewModel.orderList(arguments?.getInt(TYPE) ?: 0, true)
        }
    }

}